<template>
  <div class="payment-success-container">
    <el-card class="success-card">
      <!-- 成功图标和标题 -->
      <div class="success-header">
        <i class="el-icon-success success-icon"></i>
        <h2 class="success-title">VIP购买成功！</h2>
        <p class="success-subtitle">恭喜您成为VIP用户，享受专属特权服务</p>
      </div>

      <!-- VIP信息 -->
      <div class="vip-info">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <span class="label">VIP类型</span>
              <span class="value">{{ orderInfo.vipType }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">有效期</span>
              <span class="value">{{ orderInfo.vipDays }}天</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <span class="label">到期时间</span>
              <span class="value">{{ orderInfo.expireTime }}</span>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 自动续费签约提示 -->
      <div v-if="orderInfo.isAutoRenew" class="auto-renew-section">
        <el-divider>自动续费设置</el-divider>
        
        <el-alert
          title="您已开启自动续费"
          type="success"
          description="为了确保自动续费正常工作，请完成微信委托代扣签约"
          show-icon
          :closable="false"
          style="margin-bottom: 20px;">
        </el-alert>

        <!-- 签约状态卡片 -->
        <el-card shadow="never" class="contract-card">
          <div slot="header">
            <span>微信委托代扣签约</span>
            <el-tooltip content="签约后系统将在VIP到期前自动从您的微信账户扣费续费" placement="top">
              <i class="el-icon-question" style="margin-left: 5px; color: #909399;"></i>
            </el-tooltip>
          </div>
          
          <div class="contract-content">
            <div v-if="!contractSigned" class="contract-pending">
              <div class="contract-info">
                <i class="el-icon-warning contract-warning-icon"></i>
                <div class="contract-text">
                  <h4>需要完成委托代扣签约</h4>
                  <p>签约后，系统将在您的VIP到期前自动续费，无需手动操作</p>
                  <ul class="contract-benefits">
                    <li>✓ 自动续费，永不断档</li>
                    <li>✓ 微信安全支付保障</li>
                    <li>✓ 随时可以取消签约</li>
                  </ul>
                </div>
              </div>
              
              <div class="contract-actions">
                <el-button 
                  type="primary" 
                  size="large"
                  :loading="signing"
                  @click="handleSign">
                  <i class="el-icon-edit-outline"></i>
                  立即签约
                </el-button>
                <el-button 
                  type="text" 
                  @click="skipSigning">
                  稍后签约
                </el-button>
              </div>
            </div>
            
            <div v-else class="contract-success">
              <i class="el-icon-check contract-success-icon"></i>
              <div class="contract-text">
                <h4>签约成功！</h4>
                <p>您已成功完成微信委托代扣签约，自动续费已生效</p>
                <p class="contract-id">合约编号：{{ contractInfo.contractId }}</p>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button 
          type="primary" 
          size="large"
          @click="goToVipCenter">
          <i class="el-icon-user"></i>
          进入VIP中心
        </el-button>
        <el-button 
          size="large"
          @click="goToHome">
          <i class="el-icon-house"></i>
          返回首页
        </el-button>
      </div>

      <!-- 温馨提示 -->
      <div class="tips-section">
        <el-divider>温馨提示</el-divider>
        <div class="tips-content">
          <p><i class="el-icon-info"></i> 您可以随时在"VIP中心"管理自动续费设置</p>
          <p><i class="el-icon-info"></i> 如需取消自动续费，请在VIP到期前操作</p>
          <p><i class="el-icon-info"></i> 如有任何问题，请联系客服</p>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { signWechatContract, getWechatContractStatus } from '@/api/vip/autoRenew'
import { getVipOrder } from '@/api/vip/vipOrder'

export default {
  name: "VipPaymentSuccess",
  data() {
    return {
      // 订单信息（从路由参数或API获取）
      orderInfo: {
        orderId: null,
        vipType: 'VIP会员',
        vipDays: 30,
        amount: 29.9,
        expireTime: '2024-02-15',
        isAutoRenew: false
      },
      // 签约状态
      contractSigned: false,
      contractInfo: {
        contractId: null,
        contractCode: null
      },
      // 签约中状态
      signing: false
    }
  },
  created() {
    this.loadOrderInfo()
  },
  methods: {
    // 加载订单信息
    async loadOrderInfo() {
      try {
        // 从路由参数获取订单ID和自动续费状态
        const orderId = this.$route.query.orderId
        const isAutoRenew = this.$route.query.isAutoRenew === 'true'
        
        if (orderId) {
          this.orderInfo.orderId = orderId
          this.orderInfo.isAutoRenew = isAutoRenew
          
          // 调用API获取订单详情
          try {
            const response = await this.getOrderDetail(orderId)
            if (response.code === 200 && response.data) {
              // 更新订单信息
              this.orderInfo = {
                ...this.orderInfo,
                ...response.data,
                isAutoRenew: response.data.isAutoRenew || isAutoRenew
              }
            }
          } catch (apiError) {
            console.warn('获取订单详情失败，使用默认信息:', apiError)
            // 如果API调用失败，使用路由参数中的信息
            this.orderInfo.isAutoRenew = isAutoRenew
          }
        }
        
        // 如果开启了自动续费，检查签约状态
        if (this.orderInfo.isAutoRenew) {
          await this.checkContractStatus()
        }
      } catch (error) {
        console.error('加载订单信息失败:', error)
      }
    },
    
    // 获取订单详情
    async getOrderDetail(orderId) {
      try {
        const response = await getVipOrder(orderId)
        if (response.code === 200 && response.data) {
          return {
            code: 200,
            data: {
              vipType: response.data.vipType || 'VIP会员',
              vipDays: response.data.vipDays || 30,
              amount: response.data.amount || response.data.totalAmount,
              expireTime: response.data.expireTime,
              isAutoRenew: response.data.isAutoRenew || (this.$route.query.isAutoRenew === 'true')
            }
          }
        }
        return response
      } catch (error) {
        console.error('获取VIP订单详情失败:', error)
        // 返回默认数据
        return {
          code: 200,
          data: {
            vipType: 'VIP会员',
            vipDays: 30,
            amount: 29.9,
            expireTime: '2024-02-15',
            isAutoRenew: this.$route.query.isAutoRenew === 'true'
          }
        }
      }
    },
    
    // 检查签约状态
    async checkContractStatus() {
      try {
        const userId = this.$store.getters.userId || 1
        const response = await getWechatContractStatus(userId)
        
        if (response.code === 200 && response.data) {
          this.contractSigned = response.data.contractStatus === 1
          this.contractInfo = response.data
        }
      } catch (error) {
        console.error('检查签约状态失败:', error)
      }
    },
    
    // 处理签约
    async handleSign() {
      try {
        this.signing = true
        const userId = this.$store.getters.userId || 1
        
        const response = await signWechatContract(userId)
        if (response.code === 200) {
          this.$modal.msgSuccess('签约成功！')
          this.contractSigned = true
          this.contractInfo = response.data || {}
        } else {
          this.$modal.msgError(response.msg || '签约失败，请稍后重试')
        }
      } catch (error) {
        console.error('签约失败:', error)
        this.$modal.msgError('签约失败：' + error.message)
      } finally {
        this.signing = false
      }
    },
    
    // 跳过签约
    skipSigning() {
      this.$modal.confirm('跳过签约后，您需要在VIP中心手动完成签约才能使用自动续费功能。确定要跳过吗？', '提示', {
        confirmButtonText: '确定跳过',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.goToVipCenter()
      }).catch(() => {
        // 用户取消
      })
    },
    
    // 进入VIP中心
    goToVipCenter() {
      this.$router.push('/vip/center')
    },
    
    // 返回首页
    goToHome() {
      this.$router.push('/')
    }
  }
}
</script>

<style scoped>
.payment-success-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.success-card {
  max-width: 800px;
  width: 100%;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.success-header {
  text-align: center;
  padding: 30px 0;
}

.success-icon {
  font-size: 80px;
  color: #67C23A;
  margin-bottom: 20px;
}

.success-title {
  color: #303133;
  margin: 0 0 10px 0;
  font-size: 28px;
  font-weight: bold;
}

.success-subtitle {
  color: #909399;
  margin: 0;
  font-size: 16px;
}

.vip-info {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin: 20px 0;
}

.info-item {
  text-align: center;
}

.info-item .label {
  display: block;
  color: #909399;
  font-size: 14px;
  margin-bottom: 5px;
}

.info-item .value {
  display: block;
  color: #303133;
  font-size: 18px;
  font-weight: bold;
}

.auto-renew-section {
  margin: 30px 0;
}

.contract-card {
  border: 1px solid #e4e7ed;
}

.contract-content {
  padding: 10px 0;
}

.contract-pending {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.contract-info {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  flex: 1;
}

.contract-warning-icon {
  font-size: 24px;
  color: #E6A23C;
  margin-top: 5px;
}

.contract-text h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 16px;
}

.contract-text p {
  margin: 0 0 15px 0;
  color: #606266;
  line-height: 1.5;
}

.contract-benefits {
  list-style: none;
  padding: 0;
  margin: 0;
}

.contract-benefits li {
  color: #67C23A;
  margin-bottom: 5px;
  font-size: 14px;
}

.contract-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
  align-items: center;
}

.contract-success {
  display: flex;
  align-items: center;
  gap: 15px;
}

.contract-success-icon {
  font-size: 24px;
  color: #67C23A;
}

.contract-id {
  font-family: monospace;
  background-color: #f5f7fa;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #909399;
}

.action-buttons {
  text-align: center;
  margin: 30px 0;
  display: flex;
  gap: 15px;
  justify-content: center;
}

.tips-section {
  margin-top: 30px;
}

.tips-content {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
}

.tips-content p {
  margin: 8px 0;
  color: #606266;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.tips-content i {
  color: #409EFF;
}

@media (max-width: 768px) {
  .contract-pending {
    flex-direction: column;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
}
</style>